package com.nyist.diseasepreventionserver.service.impl;

import com.nyist.diseasepreventionserver.dto.HealthDTO;
import com.nyist.diseasepreventionserver.dto.UserDTO;
import com.nyist.diseasepreventionserver.entity.HealthDaily;
import com.nyist.diseasepreventionserver.entity.User;
import com.nyist.diseasepreventionserver.repository.HealthDAO;
import com.nyist.diseasepreventionserver.repository.UserDAO;
import com.nyist.diseasepreventionserver.service.HealthService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class HealthServiceImpl implements HealthService {

    @Autowired
    private HealthDAO healthDAO;
    @Autowired
    private UserDAO userDAO;

    @Override
    public UserDTO addDaily(HealthDTO healthDTO) {
        HealthDaily healthDaily = new HealthDaily();
        BeanUtils.copyProperties(healthDTO,healthDaily);
        //获取当前登入用户
        UserDTO userDTO = (UserDTO) SecurityUtils.getSubject().getPrincipal();
        HealthDaily daily = userDTO.getHealthDaily();
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        healthDaily.setCreateTime(simpleDateFormat.format(date));
        if (daily.getCreateTime() != null){
            healthDaily.setModifyTime(simpleDateFormat.format(date));
        }
        Integer id = daily.getId();
        healthDaily.setId(id);
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        //将填写的健康日报给予当前用户
        user.setHealthDaily(healthDaily);
        userDAO.save(user);
        //返回UserDTO给前端
        BeanUtils.copyProperties(user,userDTO);
        return userDTO;
    }
}
